// stores/theme.ts
import {defineStore} from 'pinia'
import {ref} from 'vue'

export const useThemeStore = defineStore('theme', () => {
    // 状态
    const currentTheme = ref<string>(uni.getStorageSync('theme') || 'light')
    const cookColor = ref({
        hex: "#ff6d70",
        rgba: "rgba(255,109,112,0.4)"
    })

    // 定义所有主题配置
    const themes = {
        light: {
            primaryColor: '#007aff',
            textColor: '#333',
            bgColor: '#ffffff'
        },
        dark: {
            primaryColor: '#0a84ff',
            textColor: '#f5f5f7',
            bgColor: '#1c1c1e'
        }
    }

    // 获取当前主题配置
    const theme = ref(themes[currentTheme.value])

    // 动作
    const setTheme = (themeName: 'light' | 'dark') => {
        currentTheme.value = themeName
        theme.value = themes[themeName]
        uni.setStorageSync('theme', themeName)

        // 更新全局样式类
        updateGlobalThemeClass()
    }

    function setCookColor(color: object) {
        uni.setStorageSync("cook-color", color)
        cookColor.value.hex = color.hex
        cookColor.value.rgba = `rgba(${color.rgba.r},${color.rgba.g},${color.rgba.b},0.4)`
    }

    // 切换主题
    const toggleTheme = () => {
        setTheme(currentTheme.value === 'light' ? 'dark' : 'light')
    }

    // 更新DOM类名（仅H5有效）
    const updateGlobalThemeClass = () => {
        if (typeof document !== 'undefined') {
            const app = document.getElementById('app')
            if (app) {
                app.className = `global-theme-${currentTheme.value}`
            }
        }
    }

    // 初始化
    updateGlobalThemeClass()

    return {
        currentTheme,
        theme,
        themes,
        setTheme,
        toggleTheme,
        cookColor,
        setCookColor
    }
})